<template>
  <Cascader :data="tree" :load-data="loadChildren" :change-on-select="true" trigger="hover" @on-change="setValue" v-model="value"></Cascader>
</template>

<script>
export default {
  data () {
    return {
      tree: [],
      value: []
    }
  },
  props: {
    module: {
      type: String,
      required: true
    },
    projection: String,
    setValue: {}
  },
  created () {
    this.$store.dispatch(`${this.module}/getAllList`)
  },
  computed: {
    allList () {
      return this.$store.state[this.module].allList
    },
    editNode () {
      return this.$store.state[this.module].editNode
    }
  },
  watch: {
    editNode (val) {
      this.setTree(val)
    }
  },
  methods: {
    setTree (val) {
      this.tree = []
      for (let i = 0; i < this.allList.length; i++) {
        if (!val || !val.id) {
          return
        }
        if (this.allList[i].id !== val.id) {
          const node = {
            value: this.allList[i]._links.self.href,
            label: this.allList[i].name
          }
          if (this.allList[i].childrenCount) {
            node.loading = false
            node.children = []
          }
          this.tree.push(node)
        }
      }
      console.log(this.tree)
    },
    loadChildren (item, callback) {
      item.loading = true
      this.$store.dispatch(`${this.module}/loadChildrenByParentId`, {
        item,
        cb: result => {
          if (!item.children) {
            item.children = []
          }
          for (let i = 0; i < result._embedded[this.module + 's'].length; i++) {
            if (this.editNode && this.editNode.id && result._embedded[this.module + 's'][i].id !== this.editNode.id) {
              const node = {
                value: result._embedded[this.module + 's'][i]._links.self.href,
                label: result._embedded[this.module + 's'][i].name
              }
              if (result._embedded[this.module + 's'][i].childrenCount) {
                node.loading = false
                node.children = []
              }
              item.children.push(node)
            }
          }
          item.loading = false
          // console.log(item)
          callback()
        }
      })
    }
  }
}
</script>

<style>
</style>
